<template>
  <div class="schedule-detail">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>排班详情</h2>
          <div>
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon> 返回
            </el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 排班不存在提示 -->
        <el-empty v-if="!scheduleData && !loading" description="未找到排班信息"></el-empty>

        <!-- 排班详情内容 -->
        <div v-if="scheduleData" class="detail-content">
          <div class="detail-section">
            <h3 class="section-title">基本信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="排班日期">
                {{ formatDate(scheduleData.date) }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="scheduleData.status === '正常' ? 'success' : 'danger'">
                  {{ scheduleData.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="诊室">
                {{ scheduleData.room || '未分配' }}
              </el-descriptions-item>
              <el-descriptions-item label="挂号类型">
                <el-tag>{{ scheduleData.registrationType }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">
                {{ formatDateTime(scheduleData.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ scheduleData.notes || '无' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 时间段信息 -->
          <div class="detail-section">
            <h3 class="section-title">时间段信息</h3>
            <el-table :data="scheduleData.timeSlots || []" style="width: 100%" border>
              <el-table-column label="时段" prop="period" width="100" />
              <el-table-column label="时间范围">
                <template #default="scope">
                  {{ scope.row.startTime }}-{{ scope.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="最大容量" prop="capacity" width="120" />
              <el-table-column label="剩余容量" width="120">
                <template #default="scope">
                  <el-tag :type="getCapacityTagType(
                    scheduleData.remainingCapacity?.[scope.row.period],
                    scope.row.capacity
                  )">
                    {{ scheduleData.remainingCapacity?.[scope.row.period] || 0 }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 预约列表 -->
          <div class="detail-section">
            <h3 class="section-title">预约列表</h3>
            <el-empty v-if="!appointmentList.length" description="暂无预约"></el-empty>
            <el-table v-else :data="appointmentList" style="width: 100%" border>
              <el-table-column label="预约时间" prop="timeSlot" width="120" />
              <el-table-column label="患者姓名" prop="patientName" width="120" />
              <el-table-column label="性别" width="80">
                <template #default="scope">
                  {{ scope.row.patientGender === 'male' ? '男' : '女' }}
                </template>
              </el-table-column>
              <el-table-column label="年龄" prop="patientAge" width="80" />
              <el-table-column label="联系电话" prop="patientPhone" width="140" />
              <el-table-column label="就诊原因" prop="visitReason" show-overflow-tooltip />
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { scheduleAPI, appointmentAPI } from '@/utils/api'
import { ArrowLeft } from '@element-plus/icons-vue'
import { format } from 'date-fns'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const scheduleData = ref(null)
const appointmentList = ref([])

// 根据路由参数获取排班ID
const scheduleId = route.params.id

// 获取排班详情
const getScheduleDetail = async () => {
  if (!scheduleId) {
    ElMessage.error('排班ID无效')
    return
  }

  loading.value = true
  try {
    const res = await scheduleAPI.getSchedule(scheduleId)
    if (res.success && res.data) {
      scheduleData.value = res.data
      // 获取排班关联的预约
      getScheduleAppointments()
    } else {
      ElMessage.error('获取排班详情失败')
    }
  } catch (error) {
    console.error('获取排班详情失败:', error)
    ElMessage.error('获取排班详情失败')
  } finally {
    loading.value = false
  }
}

// 获取排班关联的预约列表
const getScheduleAppointments = async () => {
  try {
    const res = await appointmentAPI.getAppointments({
      scheduleId: scheduleId,
      status: 'all'
    })
    
    if (res.success && res.data) {
      appointmentList.value = res.data.appointments || res.data.items || []
    } else {
      appointmentList.value = []
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    appointmentList.value = []
  }
}

// 获取剩余号源标签类型
const getCapacityTagType = (remaining, total) => {
  if (!total) return 'info'
  const ratio = remaining / total
  if (ratio <= 0.2) return 'danger'
  if (ratio <= 0.5) return 'warning'
  return 'success'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊'
  }
  return texts[status] || '未知'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    let date
    if (typeof dateStr === 'string') {
      if (dateStr.includes('T')) {
        date = new Date(dateStr.split('T')[0])
      } else {
        date = new Date(dateStr)
      }
    } else {
      date = new Date(dateStr)
    }
    
    if (isNaN(date.getTime())) return dateStr
    
    const weekDays = ['日', '一', '二', '三', '四', '五', '六']
    const weekDay = weekDays[date.getDay()]
    return `${format(date, 'yyyy-MM-dd')} (星期${weekDay})`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateStr
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return dateStr
    return format(date, 'yyyy-MM-dd HH:mm:ss')
  } catch (e) {
    return dateStr
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面加载时获取数据
onMounted(() => {
  getScheduleDetail()
})
</script>

<style scoped>
.schedule-detail {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #303133;
}

.el-descriptions {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-empty) {
  padding: 30px 0;
}
</style> 